package day0228;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Exer01 {

    public static void main(String[] args) {
        Catpcha catpcha = new Catpcha();

        System.out.println(catpcha.getCaptcha());

        Scanner in = new Scanner(System.in);
        System.out.println("请输入验证码：");
        String s = in.nextLine();

        boolean verify = catpcha.verify(s);

        if (verify) {
            System.out.println("验证码正确");
        } else {
            System.out.println("验证码输入错误");
        }
    }


}

class Catpcha {

    private char[] letters = new char[62];

    private String str;

    public Catpcha() {
        init();
    }

    private void init() {
        int i = 0;
        // 初始化 a - z
        for (; i < 26; i++) {
            letters[i] = (char) (97 + i);
        }
        // 初始化 A- Z
        for (int j = 0; i < 52; i++, j ++) {
            letters[i] = (char) (65 + j);
        }
        // 初始化 0 - 9
        for (int j = 0; j < 10; j++, i ++) {
            letters[i] = (char)(48 + j);
        }
        System.out.println(Arrays.toString(letters));
    }

    /**
     * 生成验证码
     * @return
     */
    public String getCaptcha() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(62);
            sb.append(letters[index]);
        }
        // 将生成的验证码保存
        str = sb.toString();
        return str;
    }

    /**
     * 校验验证码是否正确
     * @param s
     * @return
     */
    public boolean verify(String s){
        if (str != null){
            return str.equalsIgnoreCase(s);
        }
        return false;
    }
}
